<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" ref="queryRef" label-width="100">
          <el-form-item label="配置包名称：" prop="packageName">
            <el-input v-model="queryParams.packageName" placeholder="请输入配置包名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="适用仪器型号：" prop="instrumentId">
            <el-select v-model="queryParams.instrumentId" clearable filterable remote reserve-keyword
              placeholder="请输入适用仪器型号" remote-show-suffix :remote-method="remoteMethod" :loading="loading1"
              style="width: 100%">
              <el-option v-for="item in instrumentList" :key="item.instrumentId" :value="item.instrumentId"
                :label="item.name + '　' + item.code">
                {{ item.name }}&nbsp;{{ item.code }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仪器名称：" prop="instrumentName">
                <el-input v-model="queryParams.instrumentName" placeholder="请输入仪器名称" clearable
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row justify="end">
                <el-button type="success" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">仪器数据配置包列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <div>
            <el-button type="success" link icon="Plus" @click="handeleAdd">新增</el-button>
          </div>
        </el-row>

        <el-table class="business" ref="mainTableRef" v-loading="loading" :data="pagerTable" @row-click="rowClick"
          :row-class-name="tableRowClass">
          <el-table-column label="配置包名称" align="center" prop="packageName" />
          <el-table-column label="仪器型号" align="center" prop="instrumentCode" />
          <el-table-column label="仪器名称" align="center" prop="instrumentName" />
          <el-table-column label="厂商" align="center" prop="madeObject" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
            <template #default="scope">
              <el-button link type="success" @click.stop="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-tabs v-model="mainActiveName" class="demo-tabs">
        <el-tab-pane label="基本信息" name="first">
          <el-form :model="form" :rules="rules" ref="serialRef" label-width="120">
            <p class="pinformation">基础信息</p>
            <el-row>
              <el-col :span="6">
                <el-form-item label="仪器包名称：" prop="packageName">
                  <el-input clearable v-model="form.packageName" placeholder="请输入仪器包名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="数据对应关系：" prop="typeId">
                  <el-select style="width: 100%" v-model="form.typeId" clearable placeholder="请选择数据对应关系"
                    remote-show-suffix @change="typeIdChange">
                    <el-option :value="0" label="1个样品对应多个检测项目" />
                    <el-option :value="1" label="1个检测项目对应多个样品" />
                    <el-option :value="2" label="1个样品对应1个检测项目" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9" style="padding-top: 5px">
                <el-row style="justify-content: end">
                  <el-button type="success" size="small" @click="submitForm(false, 0)">保存</el-button>
                  <el-button type="success" size="small" @click="submitForm(false, 1)">应用</el-button>
                </el-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="14" v-if="form.typeId === 1">
                <el-form-item label="检测项目标识：">
                  {{ form.markDesc }}
                  <el-icon style="color: #339a35; margin-left: 15px" @click="editPackageMark">
                    <Edit />
                  </el-icon>
                </el-form-item>
              </el-col>
              <el-col :span="14" v-if="form.typeId === 0">
                <el-form-item label="样品标识：">
                  {{ form.markDesc }}
                  <el-icon style="color: #339a35; margin-left: 15px" @click="editPackageMark">
                    <Edit />
                  </el-icon>
                </el-form-item>
              </el-col>
            </el-row>

            <p class="pinformation">数据标识</p>
            <el-row>
              <el-col :span="6">
                <el-form-item label="表格标识：" prop="tableMarkName">
                  <el-input clearable v-model="form.tableMarkName" placeholder="请输入表格标识" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="开始号：" prop="tableStartNum">
                  <el-input-number clearable controls-position="right" :min="1" style="width: 100%"
                    v-model="form.tableStartNum" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="循环方式：" prop="tableLoop" @change="rulesChange">
                  <el-radio v-model="form.tableLoop" :label="0">纵向循环</el-radio>
                  <el-radio v-model="form.tableLoop" :label="1">横向循环</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item :label="'表格' + (form.tableLoop ? '行' : '列') + '数量：'" prop="loopCount"
                  v-if="form.tableLoop === 0 || form.tableLoop === 1" label-width="100">
                  <el-input-number clearable :min="1" controls-position="right" style="width: 100%"
                    v-model="form.loopCount" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="单元格分隔符：" prop="tableSplitName">
                  <el-input clearable v-model="form.tableSplitName" placeholder="请输入单元格分隔符" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-row>
                  <el-form-item label="表头过滤标识：">
                    <el-input clearable v-model="form.tableFilterName" placeholder="请输入过滤标识" />
                  </el-form-item>
                  <el-tooltip class="box-item" effect="customized" content="注: 多个标识以'$'间隔" placement="bottom">
                    <svg-icon :icon-class="'wenhao'" class="mark" style="margin: 5 0 0 10" />
                  </el-tooltip>
                </el-row>
              </el-col>
              <el-col :span="8" v-if="form.tableLoop == 0">
                <el-row>
                  <el-form-item label="数据过滤标识：">
                    <el-input clearable v-model="form.trFilterName" placeholder="请输入过滤标识" />
                  </el-form-item>
                  <el-tooltip class="box-item" effect="customized" content="注: 多个标识以'$'间隔" placement="bottom">
                    <svg-icon :icon-class="'wenhao'" class="mark" style="margin: 5 0 0 10" />
                  </el-tooltip>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
          <el-tabs v-model="activeName" @tab-change="tabChange">
            <el-tab-pane label="数据列表" name="1">
              <el-row>
                <p class="pinformation" style="margin-top: 8px">数据列表</p>
                <p class="totalStyle" style="margin-top: 5px">
                  共 {{ pagerConfigList.length }} 条数据
                </p>
                <el-row style="margin-left: 20px">
                  <el-button type="success" link icon="Plus" @click="addPagerButton">新增</el-button>
                </el-row>
              </el-row>
              <el-table :data="pagerConfigList" ref="sub1TableRef" v-loading="loading5">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="数据名称" align="center" prop="dataName" />
                <el-table-column label="数据规则" align="center" prop="dataMark">
                  <template #default="scope">
                    {{ scope.row.dataMarkDesc }}
                  </template>
                </el-table-column>
                <el-table-column label="数据标识" align="center" prop="startMarkName" />
                <el-table-column label="开始行/列" align="center" prop="startNum">
                  <template #default="scope">
                    <span v-if="scope.row.startRow">
                      第{{ scope.row.startRow }}行
                    </span>
                    <span v-if="scope.row.startCol">
                      第{{ scope.row.startCol }}列
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="结束行/列" align="center" prop="endNum">
                  <template #default="scope">
                    <span v-if="scope.row.endRow">
                      第{{ scope.row.endRow }}行
                    </span>
                    <span v-if="scope.row.endCol">
                      第{{ scope.row.endCol }}列
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="单元格分隔符" align="center" prop="dataSplitName" />
                <el-table-column label="单元格分隔符" align="center" prop="dataFilterName" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="success" @click="editpagerConfigList(scope.row.dataId)">编辑</el-button>
                    <el-button link type="success" @click="deletepagerConfigList(scope.row.dataId)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="模板对应" name="2">
              <el-row>
                <p class="pinformation" style="margin-top: 8px">模板对应</p>
                <p class="totalStyle" style="margin-top: 5px">
                  共 {{ recordsConfigList.length }} 条数据
                </p>
                <el-row style="margin-left: 20px">
                  <el-button type="success" link icon="Plus" @click="addTemplate">新增</el-button>
                </el-row>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="模板：" prop="templateName">
                    <el-input clearable v-model="form.templateName" placeholder="请输入模板" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-button type="success" style="margin-left: 10px" @click="getRecordList">查询</el-button>
                </el-col>
              </el-row>
              <el-table ref="subTableRef" :data="recordsConfigList" v-loading="loading2">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="模板编号" align="center" prop="tableCode" />
                <el-table-column label="模板名称" align="center" prop="tableName" />
                <el-table-column label="匹配数据" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="success" @click="handleCopy(scope.row)">编辑</el-button>
                    <el-button link type="success" @click="handleDelCopy(scope.row.tableId)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="谱图识别" name="second">
          <el-row>
            <el-col :span="8">
              <el-upload ref="uploadRef" :limit="1" accept=".pdf" :headers="upload.headers" :action="upload.url" drag
                :on-progress="handleFileUploadProgress" :on-error="handleUploadError" :on-exceed="handleExceed"
                :auto-upload="false" :on-change="handleOnChange" :file-list="files">
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入pdf格式文件。</span>
                  </div>
                </template>
              </el-upload>
            </el-col>
            <el-col :span="16">
              <el-row style="justify-content: space-between;">
                <el-button @click="getPtView" type="success" style="margin-left: 15px;margin-top: 8px;">谱图识别</el-button>
                <el-button @click="contentSava" type="success" :disabled="!form.packageId"
                  :style="`margin-top: ${size == 'small' ? '45px' : size == 'default' ? '40px' : '25px'};`">保存</el-button>
              </el-row>
            </el-col>
          </el-row>
          <el-scrollbar class="main_body" :height="height" ref="scrollbarRef" v-loading="loading8">
            <div v-html="textarea" style="white-space: pre-line !important;"></div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="谱图解析" name="third">
          <el-row>
            <el-col :span="8">
              <el-upload ref="upload1Ref" :limit="1" accept=".pdf" :headers="upload1.headers" :action="upload1.url" drag
                :on-progress="handleFileUploadProgress1" :on-success="handleFileSuccess1" :on-error="handleUploadError1"
                :on-exceed="handleExceed1" :auto-upload="false" :on-change="handleChange1" :on-remove="handleRemove1">
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入pdf格式文件。</span>
                  </div>
                </template>
              </el-upload>
            </el-col>
            <el-col :span="16" style="padding-left: 15px;padding-top: 8px;">
              <el-button @click="getPtView1" type="success" :disabled="!form.packageId">谱图解析</el-button>
            </el-col>
          </el-row>
          <!-- <div v-html="textarea1" style="white-space: pre-line !important;"></div> -->
          <el-table class="business" v-loading="loading6" :data="textarea1" :height="height1" ref="tableRef">
            <el-table-column label="序号" type="index" width="55" align="center" />
            <el-table-column label="样品编号" align="center" prop="1" />
            <el-table-column label="检测项目" align="center" prop="2" />
            <el-table-column :label="key" align="center" v-for="key in keys">
              <template #default="scope">
                {{ scope.row[key] }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 固定字段弹出框 -->
      <el-dialog :class="'el-dialog-theme3'" :title="title" v-model="sbwzOpen" append-to-body draggable
        :close-on-click-modal="false" @close="dialogClose">
        <el-form :model="addPagerForm" label-width="110" :rules="dialogRules" ref="SerialFormRef">
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据名称：" prop="dataName">
                <el-input clearable v-model="addPagerForm.dataName" placeholder="请输入数据名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据规则：" prop="dataMarkDesc">
                {{ addPagerForm.dataMarkDesc }}
                <el-icon style="color: #339a35; margin-left: 15px" @click="editMark">
                  <Edit />
                </el-icon>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据标识：" prop="startMarkName">
                <el-input clearable v-model="addPagerForm.startMarkName" placeholder="请输入数据标识" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据类型：" prop="dataFeature">
                <el-radio v-model="addPagerForm.dataFeature" :label="0">仪器数据</el-radio>
                <el-radio v-model="addPagerForm.dataFeature" :label="1" v-if="form.typeId != 0">样品编号</el-radio>
                <el-radio v-model="addPagerForm.dataFeature" :label="2" v-if="form.typeId != 1">检测项目</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始行/列：" prop="startNum">
                <span v-if="form.tableLoop == 1">
                  第
                  <el-input-number clearable :min="1" style="width: 35%; padding: 0 10px" :controls="false"
                    v-model="addPagerForm.startRow" />
                  行
                </span>
                <span v-if="form.tableLoop == 0">
                  第
                  <el-input-number clearable :min="1" style="width: 35%; padding: 0 10px" :controls="false"
                    v-model="addPagerForm.startCol" />
                  列
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束行/列：" prop="endNum">
                <span v-if="form.tableLoop == 1">
                  第
                  <el-input-number clearable :min="1" style="width: 35%; padding: 0 10px" :controls="false"
                    v-model="addPagerForm.endRow" />
                  行
                </span>
                <span v-if="form.tableLoop == 0">
                  第
                  <el-input-number clearable :min="1" style="width: 35%; padding: 0 10px" :controls="false"
                    v-model="addPagerForm.endCol" />
                  列
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单元格分隔符：" prop="dataSplitName">
                <el-input clearable v-model="addPagerForm.dataSplitName" placeholder="请输入单元格分隔符" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.tableLoop == 1">
              <el-form-item label="过滤标识：" prop="dataFilterName">
                <el-input clearable v-model="addPagerForm.dataFilterName" placeholder="请输入过滤标识" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="save" type="success">确 定</el-button>
            <el-button @click="sbwzOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" :title="templeTitle" v-model="templeOpen" append-to-body
        draggable :close-on-click-modal="false" @close="templeDialogClose">
        <el-form ref="templateFormRef" :model="templateForm" label-width="60">
          <el-form-item label="模板：" prop="tableId">
            <el-select v-model="templateForm.tableId" clearable filterable remote reserve-keyword placeholder="请输入模板名称"
              remote-show-suffix :remote-method="remoteMethod1" :loading="loading3" style="width: 100%"
              @change="tableIdChange">
              <el-option v-for="item in templateList" :key="item.tableId" :value="item.tableId" :label="item.tableName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <p class="pinformation">数据列表</p>
        <el-table class="business" v-loading="loading4" :data="dataList" height="50vh">
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="数据名称" align="center" prop="dataName" />
          <el-table-column label="原始记录字段" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.componentId" clearable filterable style="width: 100%">
                <el-option v-for="item in pagerList" :key="item.componentId" :value="item.componentId"
                  :label="item.componentName"></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="templeSave" type="success">保 存</el-button>
            <el-button @click="templeOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" title="编辑数据规则" v-model="markOpen" append-to-body draggable
        :close-on-click-modal="false" @close="markDialogClose" width="400">
        <el-form ref="markRef" :model="markForm" label-width="60">
          <el-form-item label="规则：" prop="dataRule">
            <el-radio v-model="markForm.dataRule" :label="0">按标识提取</el-radio>
            <el-radio v-model="markForm.dataRule" :label="1">只提取数字</el-radio>
          </el-form-item>
          <el-row v-if="markForm.dataRule === 0" :gutter="10">
            <el-col :span="10">
              <el-select v-model="markForm.markType1" placeholder="请选择" clearable>
                <el-option label="数字" :value="1" />
                <el-option label="固定标识" :value="0" />
              </el-select>
            </el-col>
            <el-col :span="8" v-if="markForm.markType1 == 0">
              <el-input v-model="markForm.markName1" placeholder="请输入" clearable />
            </el-col>
            <el-col :span="6" style="line-height: 25px">之后
              <el-button link @click="handleClearable(1)">清空</el-button>
            </el-col>
          </el-row>
          <el-row v-if="markForm.dataRule === 0" :gutter="10" style="margin-top: 10px">
            <el-col :span="10">
              <el-select v-model="markForm.markType2" placeholder="请选择" clearable>
                <el-option label="数字" :value="1" />
                <el-option label="固定标识" :value="0" />
              </el-select>
            </el-col>
            <el-col :span="8" v-if="markForm.markType2 == 0">
              <el-input v-model="markForm.markName2" placeholder="请输入" clearable />
            </el-col>
            <el-col :span="6" style="line-height: 25px">
              之前
              <el-button link @click="handleClearable(2)">清空</el-button>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="markSave" type="success">保 存</el-button>
            <el-button @click="markOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" title="编辑样品标识" v-model="packageMarkOpen" append-to-body
        draggable :close-on-click-modal="false" @close="packageMarkDialogClose" width="400">
        <el-form ref="markRef" :model="packageMarkForm" label-width="60">
          <el-form-item label="规则：" prop="packageRule">
            <el-radio v-model="packageMarkForm.packageRule" :label="0">从文件内容读取</el-radio>
            <el-radio v-model="packageMarkForm.packageRule" :label="1">从文件名读取</el-radio>
          </el-form-item>
          <el-form-item label="行标识：" prop="packageRule" v-if="packageMarkForm.packageRule == 0">
            <el-input v-model="packageMarkForm.trMark" clearable />
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="10">
              <el-select v-model="packageMarkForm.markType1" placeholder="请选择" clearable>
                <el-option label="数字" :value="1" />
                <el-option label="固定标识" :value="0" />
              </el-select>
            </el-col>
            <el-col :span="8" v-if="packageMarkForm.markType1 == 0">
              <el-input v-model="packageMarkForm.markName1" placeholder="请输入" clearable />
            </el-col>
            <el-col :span="6" style="line-height: 25px">之后
              <el-button link @click="handleClearable(1)">清空</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10" style="margin-top: 10px">
            <el-col :span="10">
              <el-select v-model="packageMarkForm.markType2" placeholder="请选择" clearable>
                <el-option label="数字" :value="1" />
                <el-option label="固定标识" :value="0" />
              </el-select>
            </el-col>
            <el-col :span="8" v-if="packageMarkForm.markType2 == 0">
              <el-input v-model="packageMarkForm.markName2" placeholder="请输入" clearable />
            </el-col>
            <el-col :span="6" style="line-height: 25px">
              之前
              <el-button link @click="handleClearable(2)">清空</el-button>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="packageMarkSave" type="success">保 存</el-button>
            <el-button @click="packageMarkOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup name="InstrumentPackage">
import {
  listPager,
  getPager,
  delPager,
  delPagerConfig,
  delPagerCopy,
  getPagerConfigForm,
  addPager,
  listTextConfig,
  addPagerConfig,
  getSelection,
  getTemplateList,
  listRecordsConfig,
  getDataTable,
  templePager,
  getPagerList,
  getMarkDesc,
  getPackageMarkDesc,
} from "@/api/system/instrPackage";
import { nextTick } from "vue";
import { getToken } from "@/utils/auth";
import axios from 'axios'
import Cookies from "js-cookie";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const total = ref(0);
const pagerTable = ref([]);
const sbwzOpen = ref(false);
const title = ref("");
const pagerConfigList = ref([]);
const recordsConfigList = ref([]);
const templateForm = ref({});
const dataList = ref([]);
const loading2 = ref(false);
const loading5 = ref(false);
const activeName = ref("1");
const fileList = ref([])
const size = ref(Cookies.get("size"))

const data = reactive({
  form: { tableStartNum: 1 },
  addPagerForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    packageName: [
      {
        required: true,
        message: "仪器包名称不能为空",
        trigger: "blur",
      },
    ],
    typeId: [
      { required: true, message: "数据对应关系不能为空", trigger: "blur" },
    ],
    tableLoop: [
      { required: true, message: "循环方式不能为空", trigger: "blur" },
    ],
    tableStartNum: [
      { required: true, message: "开始号不能为空", trigger: "blur" },
    ],
    loopCount: [{ required: true, message: "表格列不能为空", trigger: "blur" }],
    tableMarkName: [
      { required: true, message: "表格标识不能为空", trigger: "blur" },
    ],
    markDesc: [{ required: true, message: "不能为空", trigger: "change" }],
  },
  dialogRules: {
    dataName: [
      { required: true, message: "数据名称不能为空", trigger: "blur" },
    ],
    dataFeature: [
      { required: true, message: "数据类型不能为空", trigger: "blur" },
    ],
    tableId: [
      { required: true, message: "开始行/列不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules, addPagerForm, dialogRules } = toRefs(data);

/** 查询流水号配置列表 */
function getList() {
  loading.value = true;
  listPager(queryParams.value).then((response) => {
    pagerTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  textarea.value = ""
  textarea1.value = []
  form.value = { tableStartNum: 1 };
  fileList.value = []
  proxy.resetForm("serialRef");
  proxy.$refs["serialRef"]?.clearValidate();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 修改按钮操作 */
function rowClick(row) {
  handeleAdd();
  nextTick(() => {
    getPager(row.packageId).then((response) => {
      heightBright.value = row.packageId;
      form.value = response.data;
      typeIdChange();
      getTextList();
      getRecordList();
      getPtFileList(row.packageId);
    });
  })
}

const files = ref([])

function getPtFileList(packageId) {
  let url = `${import.meta.env.VITE_APP_BASE_API}/lims/instrument/package/fileData/${packageId}`
  axios({
    method: 'get',
    url: url,
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(async (res) => {
    textarea.value = res.data.data.remark
    const response = await axios({
      method: 'get',
      url: `${import.meta.env.VITE_APP_BASE_API}/system/file/download/${res.data.data.fileId}`,
      headers: { 'Authorization': 'Bearer ' + getToken() },
      responseType: 'blob'
    });
    let blob2 = new Blob([response.data], { type: 'application/pdf' })
    uploadedFile.value = window.URL.createObjectURL(blob2)
    file1.value = res.data.data.fileName
    files.value = [
      {
        url: uploadedFile.value,
        name: res.data.data.fileName
      }
    ]
  })
}

/** 提交按钮 */
function submitForm(isAuto, num) {
  return new Promise((resolve) => {
    proxy.$refs["serialRef"].validate((valid) => {
      if (valid) {
        if (form.value.typeId == 2) {
          delete form.value.markDesc;
          delete form.value.ruleList;
          delete form.value.packageRule;
        }
        if (
          !form.value.markDesc &&
          (form.value.typeId == 1 || form.value.typeId == 0)
        ) {
          proxy.$modal.msgError(
            `${form.value.typeId == 0
              ? "样品"
              : form.value.typeId == 1
                ? "检测项目"
                : ""
            }标识不能为空！`
          );
          return;
        }
        form.value.status = num;
        form.value.fileId = fileList.value[0]?.fileId
        addPager(form.value).then((res) => {
          if (!isAuto) {
            proxy.$modal.msgSuccess(res.msg);
          }
          form.value.packageId = res.data;
          heightBright.value = res.data;
          getList();
          resolve();
        });
      }
    });
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const packageId = row.packageId;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(function () {
      return delPager(packageId);
    })
    .then(() => {
      getList();
      handeleAdd();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function save() {
  if (form.value.tableLoop == 1 && !addPagerForm.value.startRow) {
    proxy.$modal.msgError("开始行不能为空！");
    return;
  }
  if (form.value.tableLoop == 0 && !addPagerForm.value.startCol) {
    proxy.$modal.msgError("开始列不能为空！");
    return;
  }
  if (
    addPagerForm.value.endRow &&
    addPagerForm.value.endRow < addPagerForm.value.startRow
  ) {
    proxy.$modal.msgError("结束行必须大于开始行！");
    return;
  }
  if (
    addPagerForm.value.endCol &&
    addPagerForm.value.endCol < addPagerForm.value.startCol
  ) {
    proxy.$modal.msgError("结束列必须大于开始列！");
    return;
  }
  proxy.$refs["SerialFormRef"].validate((valid) => {
    if (valid) {
      addPagerForm.value.packageId = form.value.packageId;
      addPagerConfig(addPagerForm.value).then((res) => {
        sbwzOpen.value = false;
        proxy.$modal.msgSuccess(res.msg);
        getTextList();
      });
    }
  });
}

function getTextList() {
  loading5.value = true;
  listTextConfig({ packageId: form.value.packageId }).then((res) => {
    pagerConfigList.value = res.data;
    loading5.value = false;
  });
}

function addPagerButton() {
  submitForm(true, 0).then(() => {
    sbwzOpen.value = true;
    title.value = "新增数据列表";
  });
}

function deletepagerConfigList(row) {
  proxy.$modal
    .confirm("是否确认删除此条数据项？")
    .then(function () {
      return delPagerConfig(row);
    })
    .then(() => {
      getTextList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function handleDelCopy(row) {
  proxy.$modal
    .confirm("是否确认删除此条数据项？")
    .then(function () {
      return delPagerCopy(form.value.packageId, row);
    })
    .then(() => {
      getRecordList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function editpagerConfigList(row) {
  submitForm(true, 0).then(() => {
    getPagerConfigForm(row).then((res) => {
      addPagerForm.value = res.data;
      sbwzOpen.value = true;
      title.value = "编辑数据规则";
    });
  });
}

function getRecordList() {
  loading2.value = true;
  listRecordsConfig({
    packageId: form.value.packageId,
    templateName: form.value.templateName,
  }).then((res) => {
    recordsConfigList.value = res.data;
    loading2.value = false;
  });
}

function handeleAdd() {
  pagerConfigList.value = [];
  recordsConfigList.value = [];
  addPagerForm.value = {};
  fileList.value = []
  heightBright.value = "";
  proxy.resetForm("serialRef");
  proxy.$refs["serialRef"]?.clearValidate();
  form.value = { tableStartNum: 1 };
  delete form.value.packageId;
  activeName.value = "1"
  proxy.$refs.uploadRef.clearFiles()
  proxy.$refs.upload1Ref.clearFiles()
  isNext.value = false
  mainActiveName.value = "first"
  textarea.value = ""
  textarea1.value = []
}

function dialogClose() {
  addPagerForm.value = {};
  proxy.$refs.SerialFormRef.clearValidate();
}

getList();

// -------------------------------------远程搜索仪器型号-----------------------------------
const loading1 = ref(false);
const instrumentList = ref([]);
function remoteMethod(val) {
  if (val) {
    loading1.value = true;
    setTimeout(() => {
      getSelection({ instrumentCode: val }).then((res) => {
        loading1.value = false;
        instrumentList.value = res.data;
      });
    }, 200);
  } else {
    instrumentList.value = [];
  }
}

// -------------------------------------远程搜索模板-----------------------------------

const loading3 = ref(false);
const templateList = ref([]);
function remoteMethod1(val) {
  if (val) {
    loading3.value = true;
    setTimeout(() => {
      getTemplateList({ tableName: val, packageId: form.value.packageId }).then(
        (res) => {
          loading3.value = false;
          templateList.value = res.data;
        }
      );
    }, 200);
  } else {
    templateList.value = [];
  }
}

//   -----------------------------------------复制功能---------------------------------------
const pagerList = ref([]);
const templeOpen = ref(false);
const templeTitle = ref("");
function addTemplate() {
  submitForm(true, 0).then(() => {
    templeOpen.value = true;
    templeTitle.value = "新增模板对应";
    getDataList();
  });
}

const loading4 = ref(false);

function getDataList(val) {
  loading4.value = true;
  getDataTable({ packageId: form.value.packageId, tableId: val }).then(
    (res) => {
      dataList.value = res.data;
      loading4.value = false;
    }
  );
}

function handleCopy(row) {
  submitForm(true, 0).then(() => {
    templeOpen.value = true;
    templeTitle.value = "编辑模板对应";
    getDataList(row.tableId);
    templateForm.value.tableId = row.tableId;
    templateList.value = [{ tableId: row.tableId, tableName: row.tableName }];
    tableIdChange(row.tableId);
  });
}

function templeDialogClose() {
  templateForm.value = {};
  dataList.value = [];
  pagerList.value = [];
  templateList.value = [];
}

function templeSave() {
  if (!templateForm.value.tableId) {
    proxy.$modal.msgError("模板不能为空！");
    return;
  }
  var isNext = false;
  dataList.value.forEach((item) => {
    if (item.componentId) {
      isNext = true;
    }
  });
  if (!isNext) {
    proxy.$modal.msgError("数据列表中原始记录至少选择一项！");
    return;
  }
  templateForm.value.componentList = dataList.value;
  templePager(templateForm.value).then((res) => {
    getRecordList();
    proxy.$modal.msgSuccess("保存成功");
    templeOpen.value = false;
  });
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 74 },
        { tableName: "sub1", bottomHeight: 21 },
        { tableName: "sub", bottomHeight: 21 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub1", bottomHeight: 21 },
        { tableName: "sub", bottomHeight: 21 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub1", bottomHeight: 21 },
  { tableName: "sub", bottomHeight: 21 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    getHeight()
    window.addEventListener("resize", getTableHeight);
    window.addEventListener("resize", getHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
  window.removeEventListener("resize", getHeight);
});

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.packageId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

function tableIdChange(val) {
  if (val) {
    getPagerList(val).then((res) => {
      pagerList.value = res.data;
    });
  }
  dataList.value.forEach((item) => {
    delete item.componentId;
  });
}

function typeIdChange(val) {
  nextTick(() => {
    getTableHeight();
    rules.value.markName = [
      {
        required: true,
        message: `${form.value.typeId === 1 ? "检测项目标识" : "样品标识"
          }不能为空`,
        trigger: "blur",
      },
    ];
  });
}

function tabChange(val) {
  nextTick(() => {
    getTableHeight();
  });
}

function rulesChange() {
  rules.value.loopCount = [
    {
      required: true,
      message: "表格" + (form.value.tableLoop ? "行" : "列") + "不能为空",
      trigger: "blur",
    },
  ];
}

const markOpen = ref(false);
const markForm = ref({});

function markDialogClose() {
  markForm.value = {};
}

function packageMarkDialogClose() {
  packageMarkForm.value = {};
}

function editMark() {
  markOpen.value = true;
  markForm.value.dataRule =
    addPagerForm.value.dataRule === 0 || addPagerForm.value.dataRule === 1
      ? addPagerForm.value.dataRule
      : 0;
  if (markForm.value.dataRule == 0) {
    addPagerForm.value.ruleList?.forEach((item) => {
      if (item.direction == 0) {
        markForm.value.markType1 = item.markType;
        markForm.value.markName1 = item.markName;
      } else {
        markForm.value.markType2 = item.markType;
        markForm.value.markName2 = item.markName;
      }
    });
  }
}

const packageMarkOpen = ref(false);
const packageMarkForm = ref({});
function editPackageMark() {
  packageMarkOpen.value = true;
  packageMarkForm.value.packageRule =
    form.value.packageRule === 0 || form.value.packageRule === 1
      ? form.value.packageRule
      : 0;
  packageMarkForm.value.trMark = form.value.trMark;
  form.value.ruleList?.forEach((item) => {
    if (item.direction == 0) {
      packageMarkForm.value.markType1 = item.markType;
      packageMarkForm.value.markName1 = item.markName;
    } else {
      packageMarkForm.value.markType2 = item.markType;
      packageMarkForm.value.markName2 = item.markName;
    }
  });
}

function markSave() {
  addPagerForm.value.dataRule = markForm.value.dataRule;
  if (markForm.value.dataRule == 0) {
    addPagerForm.value.ruleList = [
      {
        direction: 0,
        markType: markForm.value.markType1,
        markName: markForm.value.markName1,
      },
      {
        direction: 1,
        markType: markForm.value.markType2,
        markName: markForm.value.markName2,
      },
    ];
  }
  getMarkDesc({
    dataRule: addPagerForm.value.dataRule,
    ruleList: addPagerForm.value.ruleList,
  }).then((res) => {
    markOpen.value = false;
    addPagerForm.value.dataMarkDesc = res.msg;
  });
}

function packageMarkSave() {
  if (
    packageMarkForm.value.packageRule === 0 &&
    !packageMarkForm.value.trMark
  ) {
    proxy.$modal.msgError("行标识必填");
    return;
  }
  form.value.packageRule = packageMarkForm.value.packageRule;
  form.value.trMark = packageMarkForm.value.trMark;
  form.value.ruleList = [
    {
      direction: 0,
      markType: packageMarkForm.value.markType1,
      markName: packageMarkForm.value.markName1,
    },
    {
      direction: 1,
      markType: packageMarkForm.value.markType2,
      markName: packageMarkForm.value.markName2,
    },
  ];
  getPackageMarkDesc({
    packageRule: form.value.packageRule,
    ruleList: form.value.ruleList,
    trMark: packageMarkForm.value.trMark,
    typeId: form.value.typeId
  }).then((res) => {
    packageMarkOpen.value = false;
    form.value.markDesc = res.msg;
  });
}

function handleClearable(val) {
  eval("markForm.value.markType" + val + '=""');
  eval("markForm.value.markName" + val + '=""');
  eval("packageMarkForm.value.markType" + val + '=""');
  eval("packageMarkForm.value.markName" + val + '=""');
}

const mainActiveName = ref("first")
function uploadSpectrogram() {
  mainActiveName.value = "second"
}

const textarea = ref("")

const height = ref(0)
const height1 = ref(0)

function getHeight() {
  height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
  height1.value = proxy.getSubFileHeight(proxy, "tableRef");
}

watch(
  () => mainActiveName.value,
  () => {
    nextTick(() => {
      getHeight()
      getTableHeight();
    })
  }
);

const uploadedFile = ref(null)

function contentSava() {
  if (!uploadedFile.value) {
    proxy.$modal.msgError("至少选择一个文件!")
    return
  }
  upload.url = import.meta.env.VITE_APP_BASE_API + `/lims/instrument/package/saveContentByFile/${form.value.packageId}`
  fetch(uploadedFile.value)
    .then(response => response.blob())
    .then(blob => {
      const formData = new FormData();
      formData.append('file', blob, file1.value);

      axios.post(upload.url, formData, {
        headers: {
          'Authorization': 'Bearer ' + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        proxy.$modal.msgSuccess("保存成功！")
      }).catch(error => {
        console.error(error);
      });
    })
    .catch(error => {
      console.error(error);
    });
}

/*** 用户导入参数 */
const upload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/lims/instrument/package/queryContent"
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
const file1 = ref({})
function handleOnChange(file, list) {
  const contents = file.raw;
  file1.value = JSON.parse(JSON.stringify(file.name))
  // 在这里可以对文件内容进行处理或上传到服务器

  // 创建一个临时文件
  const blob = new Blob([contents], { type: file.type });
  uploadedFile.value = URL.createObjectURL(blob);
}
// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("操作失败");
}
// 超出个数
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过1个!`);
}
const loading8 = ref(false)
/** 提交上传文件 */
function getPtView() {
  if (!uploadedFile.value) {
    proxy.$modal.msgError("至少选择一个文件!")
    return
  }
  textarea.value = ""
  loading8.value = true
  upload.url = import.meta.env.VITE_APP_BASE_API + "/lims/instrument/package/queryContent"
  fetch(uploadedFile.value)
    .then(response => response.blob())
    .then(blob => {
      const formData = new FormData();
      formData.append('file', blob, file1.value);

      axios.post(upload.url, formData, {
        headers: {
          'Authorization': 'Bearer ' + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.data.code != 200) {
          proxy.$modal.msgError("文件解析失败！")
          loading8.value = false
          return
        }
        upload.isUploading = false;
        textarea.value = response.data.data
        loading8.value = false
        proxy.$modal.msgSuccess("识别成功！")
        // 请求成功后的处理
      }).catch(error => {
        // 请求失败后的处理
        console.error(error);
        loading8.value = false
      });
    })
    .catch(error => {
      console.error(error);
      loading8.value = false
    });
};

// ---------------------------------------------------------------------------------------------------
const textarea1 = ref([])
const loading6 = ref(false)
const keys = ref([])
/*** 用户导入参数 */
const upload1 = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API
});
/**文件上传中处理 */
const handleFileUploadProgress1 = (event, file, fileList) => {
  loading6.value = true
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess1 = (response, file, fileList) => {
  if (response.code != 200) {
    proxy.$modal.msgError("文件解析失败！")
    loading6.value = false
    return
  }
  upload1.isUploading = false;
  textarea1.value = response.data
  if(textarea1.value.length > 0){
  keys.value = Object.keys(textarea1.value[0]).slice(2);
}else{
  keys.value = [];
}
  loading6.value = false
  // for (let i = 0; i < response.data.length; i++) {
  //   let sampleId = response.data[i]['1'];
  //   let detectionItem = response.data[i]['2'];
  //   let peakArea = response.data[i]['峰面积'];
  //   textarea1.value += `样品编号：${sampleId}&nbsp;&nbsp;检测项目：${detectionItem}&nbsp;&nbsp;峰面积：${peakArea}<br/>`;
  // }
  proxy.$modal.msgSuccess("解析成功！")
};
const isNext = ref(false)
function handleChange1(file) {
  isNext.value = true
}

function handleRemove1(params) {
  isNext.value = false
}
// 上传失败
function handleUploadError1(err,err1,err2,err3) {
  upload1.isUploading = false;
  loading6.value = false
  proxy.$modal.msgError("操作失败:" + err.message);
}
// 超出个数
function handleExceed1() {
  proxy.$modal.msgError(`上传文件数量不能超过1个!`);
}
/** 提交上传文件 */
function getPtView1() {
  textarea1.value = []
  if (!isNext.value) {
    proxy.$modal.msgError("至少选择一个文件")
    return
  }
  upload1.url = import.meta.env.VITE_APP_BASE_API + "/lims/instrument/package/importData/" + form.value.packageId
  proxy.$refs["upload1Ref"].submit();
};

</script>

<style lang="scss" scoped>
.main_body {
  border: solid 2px #b6c2e2;
  border-radius: 10px;
  text-align: center;
  position: relative;
  overflow: hidden;
}

:deep(.el-upload-dragger) {
  padding: 10px;
}
</style>